<template>
  <div>
    <cus-allcard style="padding-bottom:10px"
                 :showTitle="false">
      <div style="display:flex;padding:24px 0px 0px 0px;flex-wrap: wrap;">
        <div class="bodyItem">
          <span style="width: 80px;">摘要名称：</span>
          <Input v-model="abstractname"
                 style="width: 200px"
                 :disabled="statuss"
                 placeholder="请输入摘要名称"
                 maxlength="15"></Input>
        </div>
        <div class="bodyItem">
          <span style="width: 80px;">摘要代码：</span>
          <Input v-model="abstractcode"
                 style="width: 200px"
                 :disabled="true"
                 placeholder="请输入摘要代码"
                 maxlength="15"></Input>
        </div>
        <div class="bodyItem">
          <span style="width: 80px;">是否在用：</span>
          <Select v-model="isvalid"
                  size="large"
                  placeholder="请选择是否在用"
                  @on-change="selectModelChange()"
                  style="width: 200px;">
            <Option :value="1">是</Option>
            <Option :value="0">否</Option>
          </Select>
        </div>
        <div class="bodyItem">
          <span style="width: 80px;">是否智能：</span>
          <Select v-model="iszhineng"
                  size="large"
                  placeholder="请选择是否智能"
                  @on-change="setIsZhineng()"
                  style="width: 200px;">
            <Option :value="1">是</Option>
            <Option :value="0">否</Option>
          </Select>
        </div>
        <div class="bodyItem">
          <span style="width: 80px;">业务类型：</span>
          <Select v-model="businesstype"
                  size="large"
                  placeholder="请选择业务类型"
                  style="width: 200px;">
            <Option v-for="item in businesstypeList"
                    :value="item"
                    :key="item">{{ item }}</Option>
          </Select>
        </div>
        <!-- // 暂时不用 -->
        <!-- <cus-Button v-if="isMultiSubjectShow"
                    class="mr_10"
                    type="primary"
                    @onClick="addSubject">添加</cus-Button> -->
      </div>
    </cus-allcard>
    <div v-if="isMultiSubjectShow"
         class="itemTable">
      <cus-allcard style="margin-top:24px;padding-top:24px"
                   :showTitle="false">

        <Table border
               :loading="form.loading"
               :columns="columnsOne"
               :data="subjectlist"
               :height="subjectlist.length>4?'353.09':subjectlist.length==0?'129':subjectlist.length*76+53"
               :size="vuex_config.tableSize">

          <template slot-scope="{ row, index }"
                    slot="subjectname">
            <div style="padding:18px 0px;">
              <Select v-model="row.subjectname"
                      size="large"
                      placeholder="请选择科目名称"
                      :disabled="row.status"
                      :transfer="true"
                      style="max-width:200px"
                      @on-change="tableSubjectnameChange(index,row.subjectname)">
                <Option v-for="item in subjectlistSelect"
                        :value="item.subjectname"
                        :key="item.subjectname">{{ item.subjectname }}</Option>
              </Select>
            </div>
          </template>
          <template slot-scope="{ row, index }"
                    slot="direction">
            <div style="padding:18px 0px;">
              <Select v-model="row.direction"
                      size="large"
                      placeholder="请选择收付"
                      :disabled="row.status"
                      :transfer="true"
                      style="max-width:200px"
                      @on-change="tableDirection(index,row.direction)">
                <Option :value="0">收</Option>
                <Option :value="1">付</Option>
              </Select>
            </div>
          </template>
          <template slot-scope="{ index }"
                    slot="operation">
            <div class="flex">
              <cus-button type="text"
                          size="small"
                          style='color:#FF4746;padding:0 8px;'
                          @onClick="clearCli(index)">
                删除
              </cus-button>
            </div>
          </template>
        </Table>

      </cus-allcard>
    </div>
    <!-- 使用粘性定位 -->
    <div class="sticky-button">
      <cus-Button class="mr_10"
                  type="default"
                  @onClick="returnButton">返回</cus-Button>
      <!-- 新增进来 -->
      <cus-Button v-if="addOrEidt === 'add'"
                  class="mr_10"
                  type="primary"
                  @onClick="addAbstractApi">保存</cus-Button>
      <!-- 修改进来 -->
      <cus-Button v-if="addOrEidt !== 'add'"
                  class="mr_10"
                  type="primary"
                  @onClick="modifyZhinengApi">保存</cus-Button>
    </div>
  </div>
</template>
<script>
import {
  getNewAbstractCode,
  getBusiniessAccountBookId,
  addAbstract,
  addZhineng,
  getSubjectToCertificate,
  getZhineng,
  modifyZhineng
} from '@/api/businessAccountingApi/essentialInformationApi'
export default {
  data () {
    return {
      form: {
        loading: false,
        name: '',
        startTime: '',
        endTime: ''
      },
      statuss: false, // 新增进来false名字能修改，修改进来true名字不能修改
      addOrEidt: 'add', // 区分时添加进来 还是修改进来 add/edit

      abstracttype: 0, // 类型(0经费;1粮秣)
      isvalid: 1, // 是否在用(0否;默认1是)
      userid: 0, // 用户id
      isInit: 1, // 是否初为始化摘要(0是;1否) 写死为1
      abstractcode: '', // 摘要代码
      abstractname: '', // 摘要名称
      iszhineng: 0, // 是否智能(默认0否;1是)
      businesstype: '', // 业务类型
      businesstypeList: [], // 业务类型列表
      // 表格每次添加的初始模板
      subjectitem: {
        subjectid: 0, // 科目id
        subjectname: '', // 科目名称
        subjectcode: '', // 科目编码
        direction: -1 // 0收方 1付方
      },
      subjectlist: [], // 表格列表 科目(智能摘要时必填)
      subjectlistSelect: [], // 表格科目名称选择器列表
      accountbookId: 0, // 账簿id
      isMultiSubjectShow: false, // 表格是否显示
      // 经费账-表头
      columnsOne: [
        {
          title: '序号',
          type: 'index',
          align: 'center'
        },

        {
          title: '科目名称',
          slot: 'subjectname',
          align: 'center'
        },
        {
          title: '科目方向',
          slot: 'direction',
          align: 'center'
        }
        // 暂时不用
        // ,
        // {
        //   title: '操作',
        //   slot: 'operation',
        //   align: 'center'
        // }
      ]
    }
  },

  mounted () {
  console.log(12345);
    this.addOrEidt = this.$route.query.addOrEidt// 区分时添加进来 还是修改进来 add/edit
    if (this.addOrEidt === 'add') { // 添加进来页面
      this.statuss = false// 新增进来false名字能修改，修改进来true名字不能修改
      this.accountbookId = this.$route.query.accountbookId// 账簿id
      this.abstracttype = this.$route.query.subjecttype// 类型(0经费;1粮秣)
      this.getNewAbstractCodeApi()// 添加摘要时获取摘要代码  接口
      this.getBusiniessAccountBookIdApi()// 根据类型、账簿id查询业务类型(不分页) 接口
      this.getSubjectToCertificateApi()// 根据类型、用户id和账簿id查询所有在用科目(不分页) 接口
    } else { // 修改进来页面
      this.statuss = true// 新增进来false名字能修改，修改进来true名字不能修改
      this.accountbookId = this.$route.query.accountbookId// 账簿id
      this.abstracttype = this.$route.query.subjecttype// 类型(0经费;1粮秣)
      this.getBusiniessAccountBookIdApi()// 根据类型、账簿id查询业务类型(不分页) 接口
      this.getSubjectToCertificateApi()// 根据类型、用户id和账簿id查询所有在用科目(不分页) 接口
      setTimeout(() => {
        this.abstractname = this.$route.query.abstractname// 摘要名称
        this.getZhinengApi()
        this.abstractcode = this.$route.query.abstractcode// 摘要代码
        this.isvalid = Number(this.$route.query.isvalid)// 是否在用
        this.iszhineng = Number(this.$route.query.iszhineng)// 是否智能
        this.setIsZhineng() // 表格是否显示
        this.businesstype = this.$route.query.businesstype// 业务类型
        this.isInit = this.$route.query.isinit // 是否初始化
      }, 100)
    }
    // 函数时提示变成3秒消失
    this.$Message.config({
      top: 50,
      duration: 3
    })
  },
  // 销毁函数时提示变回1.5秒消失
  beforeDestroy () {
    this.$Message.config({
      top: 50,
      duration: 1.5
    })
  },
  methods: {
    // 添加摘要时获取摘要代码  接口
    getNewAbstractCodeApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        getNewAbstractCode({
          userid: this.vuex_user.base.id, // 用户id
          abstracttype: this.abstracttype // 账簿id
        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            this.abstractcode = res.newabstractcode
            resolve()
          } else {
            this.$Message.error(res.resultmsg)
          }
        })
      })
    },
    // 根据类型、账簿id查询业务类型(不分页)  接口
    getBusiniessAccountBookIdApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        getBusiniessAccountBookId({
          userid: this.vuex_user.base.id, // 用户id
          accountBookId: this.accountbookId, // 账簿id
          iszhineng: this.iszhineng, // 是否智能
          abstractType: this.abstracttype //  摘要类型(0经费;1粮秣)
        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            this.businesstypeList = res.data
            resolve()
          } else {
            this.$Message.error(res.resultmsg)
          }
        })
      })
    },
    // 添加摘要 接口
    addAbstractApi () {
      if (this.abstractname === '') {
        this.$Message.info('摘要名称不能为空')
        return
      }
      if (this.businesstype === '') {
        this.$Message.info('业务类型不能为空')
        return
      }
      if (this.iszhineng === 0) { // 是否智能(默认0否;1是) 非智能
        this.form.loading = true
        return new Promise((resolve) => {
          addAbstract({
            abstracttype: this.abstracttype, //  摘要类型(0经费;1粮秣)
            isvalid: this.isvalid, // 是否在用(0否;1是)
            userid: this.vuex_user.base.id, // 用户id
            isInit: this.isInit, // 是否初为始化摘要(0是;1否)
            abstractcode: this.abstractcode, // 编码
            abstractname: this.abstractname, // 名称
            iszhineng: this.iszhineng, // 是否智能
            businesstype: this.businesstype, // 业务类型
            subjectlist: this.subjectlist, // 科目(智能摘要时必填)
            accountbookId: this.accountbookId // 账簿id
          }).then((res) => {
            this.form.loading = false
            if (res.errorcode === 0) {
              this.$Message.success(res.resultmsg)
              this.returnButton()// 返回按钮
              resolve()
            } else {
              this.$Message.error(res.resultmsg)
            }
          })
        })
      } else { // 是否智能(默认0否;1是) 智能
        // 判断表格里是否有空的值，有不往下执行
        let ass = false
        this.subjectlist.forEach(element => {
          if (element.subjectname === '') {
            this.$Message.info('表格科目名称为空不能保存')
            ass = true
            return ass
          }
          if (element.direction === -1) {
            this.$Message.info('表格科目方向为空不能保存')
            ass = true
            return ass
          }
        })
        if (ass) {
          return
        }
        this.form.loading = true
        return new Promise((resolve) => {
          addZhineng({
            abstracttype: this.abstracttype, //  摘要类型(0经费;1粮秣)
            isvalid: this.isvalid, // 是否在用(0否;1是)
            userid: this.vuex_user.base.id, // 用户id
            isInit: this.isInit, // 是否初为始化摘要(0是;1否)
            abstractcode: this.abstractcode, // 编码
            abstractname: this.abstractname, // 名称
            iszhineng: this.iszhineng, // 是否智能
            businesstype: this.businesstype, // 业务类型
            subjectList: JSON.stringify(this.subjectlist), // 科目(智能摘要时必填)
            accountbookId: this.accountbookId // 账簿id
          }).then((res) => {
            this.form.loading = false
            if (res.retCode === 0) {
              this.$Message.success(res.retMsg)
              this.returnButton()// 返回按钮
              resolve()
            } else {
              this.$Message.error(res.retMsg)
            }
          })
        })
      }
    },
    // 添加摘要 接口
    modifyZhinengApi () {
      // 判断表格里是否有空的值，有不往下执行
      let ass = false
      this.subjectlist.forEach(element => {
        if (element.subjectname === '') {
          this.$Message.info('表格科目名称为空不能保存')
          ass = true
          return ass
        }
        if (element.direction === -1) {
          this.$Message.info('表格科目方向为空不能保存')
          ass = true
          return ass
        }
      })
      if (ass) {
        return
      }
      this.form.loading = true
      return new Promise((resolve) => {
        modifyZhineng({
          abstracttype: this.abstracttype, //  摘要类型(0经费;1粮秣)
          isvalid: this.isvalid, // 是否在用(0否;1是)
          userid: this.vuex_user.base.id, // 用户id
          isInit: this.isInit, // 是否初为始化摘要(0是;1否)
          abstractcode: this.abstractcode, // 编码
          abstractname: this.abstractname, // 名称
          iszhineng: this.iszhineng, // 是否智能
          businesstype: this.businesstype, // 业务类型
          subjectlist: JSON.stringify(this.subjectlist) // 科目(智能摘要时必填)
        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            this.$Message.success(res.resultmsg)
            this.returnButton()// 返回按钮
            resolve()
          } else {
            this.$Message.error(res.resultmsg)
          }
        })
      })
    },
    // 根据类型、用户id和账簿id查询所有在用科目(不分页) 接口
    getSubjectToCertificateApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        getSubjectToCertificate({
          userid: this.vuex_user.base.id, // 用户id
          accountBookId: this.accountbookId, // 账簿id
          subjectType: this.abstracttype //  摘要类型(0经费;1粮秣)
        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            console.log('table111',res.subjectlist);
            this.subjectlistSelect = res.subjectlist
            resolve()
          } else {
            this.$Message.error(res.resultmsg)
          }
        })
      })
    },
    // 修改功能根据名字查找智能下的表格数据 接口
    getZhinengApi () {
      this.form.loading = true
      return new Promise((resolve) => {
        getZhineng({
          abstractname: this.abstractname,
          userid: this.vuex_user.base.id // 用户id
        }).then((res) => {
          this.form.loading = false
          if (res.errorcode === 0) {
            console.log('表格数据',res.zhinenglist);
            // this.subjectlist = res.zhinenglist
            res.zhinenglist.forEach((element, index) => {
              this.subjectlist[index].subjectid = element.subjectId
              this.subjectlist[index].subjectname = element.subjectname
              this.subjectlist[index].subjectcode = element.subjectcode
              this.subjectlist[index].direction = element.direction
              this.subjectlist[index].status = true
            })
            resolve()
          } else {
            this.$Message.error(res.resultmsg)
          }
        })
      })
    },
    // 返回按钮
    returnButton () {
      this.$router.push({
        // path: '/view/accountBookMaintenance/grainAndFodderSubject'
        name: '业务摘要'
        // query: {
        //   grainAndFodderSubjectItem: 'grainAndFodderSubjectItem'
        // }
      })
    },

    // 是否智能选择器改变回调
    setIsZhineng () {
      this.getBusiniessAccountBookIdApi() // 根据类型、账簿id查询业务类型(不分页)  接口
      this.subjectlist = [] // 表格清空
      if (this.iszhineng === 0) { // 否  是否智能(默认0否;1是)
        this.isMultiSubjectShow = false // 关闭表格
      } else { // 是  是否智能(默认0否;1是)
        this.isMultiSubjectShow = true // 开启表格
        this.addSubject()
        this.addSubject()
      }
    },
    // 添加按钮
    addSubject () {
      this.subjectlist.push(JSON.parse(JSON.stringify(this.subjectitem)))
    },
    // 表格科目名称改变回调
    tableSubjectnameChange (index, value) {
      this.subjectlistSelect.forEach(element => {
        if (element.subjectname === value) {
          this.subjectlist[index].subjectid = element.subjectId
          this.subjectlist[index].subjectname = element.subjectname
          this.subjectlist[index].subjectcode = element.subjectcode
          this.subjectlist[index].subjectfullname = element.subjectfullname
        }
      })
    },
    // 表格科目方向改变回调
    tableDirection (index, value) {
      this.subjectlist[index].direction = value
    },
    // 表格清除按钮
    clearCli (index) {
      this.subjectlist.splice(index, 1)
      if (this.subjectlist.length < 2) {
        this.addSubject()
        this.$Message.info('至少存在两个科目！')
      }
      // this.zhi.splice(index, 1)
    }
  }
}
</script>
<style lang="less" scoped>
.bodyItem {
  display: flex;
  align-items: center;
  margin-right: 12px;
  margin-bottom: 14px;
}
//  按钮的粘性定位
.sticky-button {
  position: sticky;
  bottom: 0;
  background: #f2f5f9;
  display: flex;
  justify-content: flex-end;
  padding: 16px 0px 16px 0px;
}
</style>
